package proccess

import (
	"context"
	. "gitee.com/youbeiwuhuan/go-xxljob-executor/biz/model"
	. "gitee.com/youbeiwuhuan/go-xxljob-executor/global"
	"go.uber.org/zap"
	"time"
)

const (
	REGISTRY_IDLE_SECOND = 30
)

const (
	EXECUTOR = "EXECUTOR"
	ADMIN    = "ADMIN"
)

// 注册处理器
type ExecutorRegistryProccessor struct {
	appname string //应用名
	address string // 注册地址

	cancel context.CancelFunc
}

func NewExecutorRegistryProccessor(appname string, address string) *ExecutorRegistryProccessor {

	return &ExecutorRegistryProccessor{
		appname: appname,
		address: address,
	}

}

func (t *ExecutorRegistryProccessor) Start() {
	ctx, cancle := context.WithCancel(context.Background())
	t.cancel = cancle

	go func() {

	LOOP_TRIGGER:
		for {
			select {
			case <-ctx.Done():
				Logger.Info(">>>>>stop")
				break LOOP_TRIGGER
			default:
				succ := false
				for i := 0; i < 3 && !succ; i = i + 1 {
					succ = t.doReistry()
				}

				time.Sleep(time.Duration(REGISTRY_IDLE_SECOND) * time.Second)
			}

		}
	}()

}

func (t *ExecutorRegistryProccessor) Stop() {
	t.removeReistry()
	t.cancel()
}

func (t *ExecutorRegistryProccessor) doReistry() (succ bool) {
	defer func() {
		if r := recover(); r != nil {
			Logger.Error("Run pannic ,", zap.Any("err", r))
		}
	}()

	succ = false

	for _, adminBiz := range AdminBizList {
		rt := adminBiz.Registry(RegistryParam{
			RegistryGroup: EXECUTOR,
			RegistryKey:   t.appname,
			RegistryValue: t.address,
		})

		Logger.Debug("---------------" + rt.String())

		if SUCCESS_CODE == rt.Code {
			succ = true
			break
		}
	}

	return succ

}

func (t *ExecutorRegistryProccessor) removeReistry() (succ bool) {
	defer func() {
		if r := recover(); r != nil {
			Logger.Error("Run pannic ,", zap.Any("err", r))
		}
	}()

	succ = false

	for _, adminBiz := range AdminBizList {
		rt := adminBiz.RegistryRemove(RegistryParam{
			RegistryGroup: EXECUTOR,
			RegistryKey:   t.appname,
			RegistryValue: t.address,
		})
		if SUCCESS_CODE == rt.Code {
			succ = true
			break
		}
	}

	return succ
}
